package net.seninp.fdata.data;

public class MeasurementsGrid {

  private static final Double LATD_BORDER_INCRIMENT = 0.0001;
  private static final Double LOND_BORDER_INCRIMENT = 0.0001;
  private Double minLatd;
  private Double maxLatd;
  private Double minLond;
  private Double maxLond;
  private Cell[][] cells;

  public MeasurementsGrid(Double minLatd, Double maxLatd, Double minLond, Double maxLond,
      Integer gridLatdSize, Integer gridLondSize) {
    this.minLatd = minLatd;
    this.maxLatd = maxLatd;
    this.minLond = minLond;
    this.maxLond = maxLond;

    Double stepLatd = (this.maxLatd - this.minLatd) / gridLatdSize.doubleValue();
    Double stepLond = (this.maxLond - this.minLond) / gridLondSize.doubleValue();

    this.cells = new Cell[gridLatdSize][gridLondSize];

    for (int i = 0; i < gridLatdSize; i++) {
      for (int j = 0; j < gridLondSize; j++) {
        Double latStart = this.minLatd + stepLatd * i;
        Double latEnd = this.minLatd + stepLatd * (i + 1);
        Double lonStart = this.minLond + stepLond * j;
        Double lonEnd = this.minLond + stepLond * (j + 1);
        if (i == gridLatdSize - 1) {
          latEnd = latEnd + LATD_BORDER_INCRIMENT;
        }
        if (j == gridLondSize - 1) {
          lonEnd = lonEnd + LOND_BORDER_INCRIMENT;
        }
        cells[i][j] = new Cell(latStart, latEnd, lonStart, lonEnd);
      }
    }
  }

  public Cell put(Measurement m) {
    for (int i = 0; i < cells.length; i++) {
      for (int j = 0; j < cells[0].length; j++) {
        if (cells[i][j].add(m)) {
          return cells[i][j];
        }
      }
    }
    return null;
  }

  public int sizeX() {
    return cells.length;
  }

  public int sizeY() {
    if (cells.length > 0) {
      return cells[1].length;
    }
    return 0;
  }

  public Cell getCell(int i, int j) {
    return this.cells[i][j];
  }
}
